package com.example.espressotests


import androidx.recyclerview.widget.RecyclerView
import androidx.test.espresso.Espresso
import androidx.test.espresso.action.ViewActions.*
import androidx.test.espresso.assertion.ViewAssertions.matches
import androidx.test.espresso.contrib.RecyclerViewActions
import androidx.test.espresso.matcher.ViewMatchers.*
import androidx.test.espresso.web.assertion.WebViewAssertions
import androidx.test.espresso.web.sugar.Web.onWebView
import androidx.test.espresso.web.webdriver.DriverAtoms
import androidx.test.espresso.web.webdriver.DriverAtoms.findElement
import androidx.test.espresso.web.webdriver.DriverAtoms.webClick
import androidx.test.espresso.web.webdriver.Locator
import androidx.test.ext.junit.runners.AndroidJUnit4
import androidx.test.filters.LargeTest
import androidx.test.rule.ActivityTestRule
import org.hamcrest.Matchers
import org.junit.Rule
import org.junit.Test
import org.junit.runner.RunWith

@LargeTest
@RunWith(AndroidJUnit4::class)
class MainActivityTest {

    @Rule
    @JvmField
    var mActivityTestRule = ActivityTestRule(MainActivity::class.java)

    @Test
    fun mainActivityTest() {
        Espresso.onView(withId(R.id.edit1)).perform(typeText("52"), closeSoftKeyboard())
        Espresso.onView(withId(R.id.edit2)).perform(typeText("88"), closeSoftKeyboard())
        Espresso.onView(withId(R.id.btn)).perform(click())

        Espresso.onView(withId(R.id.text1)).check(matches(withText("结果：140")))
    }

    @Test
    fun testRecycleView() {
        Espresso.onView(withText("跳转到RecycleViewActivity")).perform(click())
        Espresso.onView(withText("第四列")).check(matches(isDisplayed())).perform(click())
        Espresso.onView(withText("确定")).perform(click())

        Espresso.onView(withText("第五列")).check(matches(isDisplayed())).perform(click())
        Espresso.pressBack()

        Espresso.onView(withId(R.id.recycle_view)).perform(
            RecyclerViewActions.actionOnItemAtPosition<RecyclerView.ViewHolder>(
                14,
                click()
            )
        )
        Espresso.onView(withText("确定")).perform(click())
        Espresso.pressBack()
    }

    @Test
    fun testWebView() {
        Espresso.onView(withId(R.id.btn2)).perform(click())

        onWebView().withElement(findElement(Locator.NAME, "word"))
            .perform(DriverAtoms.webKeys("android"))
            .withElement(findElement(Locator.ID, "index-bn"))
            .perform(webClick())
            .withElement(findElement(Locator.ID, "results"))
            .check(
                WebViewAssertions.webMatches(
                    DriverAtoms.getText(),
                    Matchers.containsString("android")
                )
            )
        Espresso.pressBack()
    }
}
